/**
 * index
 */
define(function(require) {
    var $ = require('jquery');
    var com = require('./common');

    require('base');
    var get_screen_tip = $.cookie('screen_tip');

    /*分辨率检测*/
    check_px = function(){
        var window_w = $(window).outerWidth(),
            window_h = $(window).outerHeight();
        console.log('窗口宽度为:'+window_w);
        console.log('窗口高度为:'+window_h);
        if(window_w < 1370 || window_h < 770){
            if(get_screen_tip){
                return false;
            };
            require.async('box',function(){
                $.box('您的屏幕分辨率较低，会影响页面的显示效果，<br />建议将分辨率调至1440x900以上。',{
                    title:'提示',
                    bgclose:false,
                    width:420,
                    onshow:function(){
                        $.cookie('screen_tip','true',{ expires: 999 });
                    }
                })
            })
        }
    };

    /*浏览器类型提示*/
    browser_tip = function(){
        require.async('box',function(){
            $.box($('.ieTip'),{
                title:'提示',
                hook:'ieTipBox',
                bgclose:false,
                onclose:function(){
                    setTimeout(function(){
                        check_px()
                    },500)
                }
            })
        })
    };

    /*浏览器类型检测*/
    function IEVersion() {
        var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串  
        var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器  
        var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器  
        var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
        if(isIE) {
            var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
            reIE.test(userAgent);
            var fIEVersion = parseFloat(RegExp["$1"]);
            if(fIEVersion == 7) {
                return 7;
            } else if(fIEVersion == 8) {
                return 8;
            } else if(fIEVersion == 9) {
                return 9;
            } else if(fIEVersion == 10) {
                return 10;
            } else {
                return 6;//IE版本<=7
            }   
        } else if(isEdge) {
            return 'edge';//edge
        } else if(isIE11) {
            return 11; //IE11  
        }else{
            return -1;//不是ie浏览器
        }
    };
    
    if(IEVersion() != '-1'){
        browser_tip()
    }else{
        check_px()
    }
    /*浏览器类型检测 end*/


    com.layoutSet();

    //数字处理
    com.digital_num('digital_num');

    //预警布局
    axios.get(com.api.alerted).then(function(response){
        for (var i = 0; i < response.data.num.length; i++) {
            com.chart5("chart"+i+"",response.data.num[i].data,response.data.num[i].name);
        };
    });

    $('.filter_box').each(function(){
        var parent_height = $('.filter_box').parents('.sbox').outerHeight();
        $(this).height(parent_height-3);
    });
    $(".filter_box dt").click(function(){
        if(!$(this).hasClass('no_dd')){
            $(this).parents('.span-6').siblings().find('dt').removeClass('active');
            $(this).parents('.span-6').siblings().find('dd').slideUp("fast");
            $(this).next("dd").slideToggle("fast").siblings("dd:visible").slideUp("fast");
            $(this).toggleClass("active");
            $(this).siblings(".active").removeClass("active");
        }else{
            $('.filter_box').find('dt').removeClass('active');
            $('.filter_box').find('dd').slideUp("fast");
        }
    });
    
    //地图区域
    var main_height = $('.indexMain').outerHeight();
    $('.map_main,.map_container').height(main_height - 10);

    var map,
        num_show_status = false;
    map_function = function(id,area,map_data,area_data){

        //百度地图
        map = new BMap.Map(id, { 
            enableMapClick:false,
            minZoom: 12,
            maxZoom: 16
        });

        //地图基础样式
        map.setMapStyle({
            styleJson: [
                  {
                            "featureType": "all",
                            "elementType": "geometry",
                            "stylers": {
                                      "color":"#0a7aceff",
                                      "lightness": 1,
                                      "saturation": 100
                            }
                  },
                  {
                            "featureType": "all",
                            "elementType": "labels",
                            "stylers": {
                                      "visibility": "off"
                            }
                  },
                  {
                            "featureType": "poilabel",
                            "elementType": "all",
                            "stylers": {
                                      "visibility": "off"
                            }
                  },
                  {
                            "featureType": "road",
                            "elementType": "all",
                            "stylers": {
                                      "visibility": "off"
                            }
                  },
                  {
                            "featureType": "green",
                            "elementType": "all",
                            "stylers": {
                                      "visibility": "off"
                            }
                  },
                  {
                            "featureType": "water",
                            "elementType": "all",
                            "stylers": {
                                      "visibility": "off"
                            }
                  },
                  {
                            "featureType": "manmade",
                            "elementType": "all",
                            "stylers": {
                                      "visibility": "off"
                            }
                  },
                  {
                            "featureType": "building",
                            "elementType": "all",
                            "stylers": {
                                      "visibility": "off"
                            }
                  }
        ]
        });

        map.enableScrollWheelZoom();    //允许滚动缩放
        //map.disableDragging();          //禁止拖动
        map.disableDoubleClickZoom();   //禁止双击缩放
        map.addControl(new BMap.NavigationControl({ anchor:BMAP_ANCHOR_BOTTOM_RIGHT, type:BMAP_NAVIGATION_CONTROL_LARGE,showZoomInfo:true}));

        //start
        var blist = [];
        var districtLoading = 0;

        function addDistrict(districtName) {
            //使用计数器来控制加载过程
            districtLoading++;
            var bdary = new BMap.Boundary();
            bdary.get(districtName, function (rs) {     //获取行政区域
                var count = rs.boundaries.length;       //行政区域的点有多少个
                if (count === 0) {
                    alert('未能获取当前输入行政区域');
                    return;
                }
                for (var i = 0; i < count; i++) {
                    blist.push({ points: rs.boundaries[i], name: districtName });
                };
                //加载完成区域点后计数器-1
                districtLoading--;
                if (districtLoading == 0) {
                    //全加载完成后画端点
                    drawBoundary();
                }
            });
        }

        function drawBoundary(street_points) {
            var pointArray = [];

            //定义中国东南西北端点，作为第一层
            var pNW = { lng: 73.0, lat: 59.0}
            var pNE = { lng: 136.0, lat: 59.0 }
            var pSE = { lng: 136.0, lat: 3.0 }
            var pSW = { lng: 73.0, lat: 3.0 }
            //向数组中添加一次闭合多边形，并将西北角再加一次作为之后画闭合区域的起点
            var pArray = [];
            pArray.push(pNW);
            pArray.push(pSW);
            pArray.push(pSE);
            pArray.push(pNE);
            pArray.push(pNW);

            var blist_length;
            if(street_points){
                blist_length = 1;
            }else{
                blist_length = blist.length;
            }
            //循环添加各闭合区域
            for (var i = 0; i < blist_length; i++) {
                //添加多边形层并显示
                if(street_points){
                    var sp_arr = '';
                    for (var i = 0; i < street_points.length; i++) {
                        sp_arr+= street_points[i].lng+','+street_points[i].lat+';'
                    };
                    sp_arr += street_points[0].lng+','+street_points[0].lat;
                    var ply = new BMap.Polygon(sp_arr, { strokeWeight: 3, strokeColor: "#ff6600", fillOpacity: 0.01 });
                }else{
                    //添加显示用标签层
                    var label = new BMap.Label(blist[i].name, { offset: new BMap.Size(20, -10) });
                    label.hide();
                    map.addOverlay(label);
                    var ply = new BMap.Polygon(blist[i].points, { strokeWeight: 3, strokeColor: "#ff6600", fillOpacity: 0.01 });
                    
                    //建立多边形覆盖物
                    ply.name = blist[i].name;
                    ply.label = label;

                    //添加名称标签层
                    var centerlabel = new BMap.Label(blist[i].name, { offset: new BMap.Size(0, 0) });
                    centerlabel.setPosition(ply.getBounds().getCenter());
                    //map.addOverlay(centerlabel);
                };
                
                //ply.addEventListener("click", click);
                //ply.addEventListener("mouseover", mouseover);
                //ply.addEventListener("mouseout", mouseout);
                //ply.addEventListener("mousemove", mousemove);
                map.addOverlay(ply);

                //将点增加到视野范围内
                var path = ply.getPath();
                pointArray = pointArray.concat(path);
                //将闭合区域加到遮蔽层上，每次添加完后要再加一次西北角作为下次添加的起点和最后一次的终点
                pArray = pArray.concat(path);
                pArray.push(pArray[0]);
                
            }

            //限定显示区域，需要引用api库
            var boundply = new BMap.Polygon(pointArray);
            BMapLib.AreaRestriction.setBounds(map, boundply.getBounds());
            map.setViewport(pointArray);    //调整视野 

            //添加遮蔽层
            var plyall = new BMap.Polygon(pArray, { strokeOpacity: 0.0000001, strokeColor: "#132234", strokeWeight: 0.00001, fillColor: "#132234", fillOpacity:1 }); //建立多边形覆盖物
            map.addOverlay(plyall);
        }


        //添加街区覆盖
        function addOverly(data,color) {
            var ps = new Array();
            for (var i = 0; i < data.length; i++) {
                ps.push(new BMap.Point(data[i].lng, data[i].lat));
            }
            var polygon = new BMap.Polygon(ps, { 
                strokeOpacity: 0.0000001, 
                strokeColor:'#003f6d', 
                strokeWeight: 0.00001, 
                fillColor: '#003f6d', 
                fillOpacity:0.5
            });
            polygon.addEventListener("mouseover", function(evt){
                polygon.setFillColor('#333333');
            });
            polygon.addEventListener("mouseout", function(evt){
                polygon.setFillColor('#003f6d');
            });
            return polygon;
        };

        //添加标注
        function addLabel(lng,lat,title){
            var label_a = new BMap.Label(title, {
              position : new BMap.Point(lng,lat),   // 指定文本标注所在的地理位置
              offset   : new BMap.Size(-15, -5)     //设置文本偏移量
            });
            label_a.setStyle({
                borderWidth:0,
                backgroundColor:'transparent',
                color:'#dddddd'
            });
            map.addOverlay(label_a);
        };


        var campus_polygon = new Array(),
            all_info = new Array();
        showArea = function(data){
            if(data.length > 1){
                for (var i = 0; i < data.length; i++) {
                    var AO = addOverly(data[i].data);
                    map.addOverlay(AO);                 //添加多边形覆盖
                    campus_polygon.push(AO);            //将区域信息加入数组，用来验证点击
                    all_info.push({'id':data[i].data_id,'title':data[i].title});     //将信息加入数组，用来输出
                    addLabel(data[i].center.lng,data[i].center.lat,data[i].title);  //添加标注
                }
            }else{
                var AO = addOverly(data[0].data);
                map.addOverlay(AO);                 //添加多边形覆盖
                campus_polygon.push(AO);            //将区域信息加入数组，用来验证点击
                all_info.push({'id':data[0].data_id,'title':data[0].title});     //将信息加入数组，用来输出
                addLabel(data[0].center.lng,data[0].center.lat,data[0].title);  //添加标注
            }
        }

        function polygonCheck(pt){
            var campusMark = new Array();
            for (var i = 0; i < campus_polygon.length; i++) {
                var result = BMapLib.GeoUtils.isPointInPolygon(pt, campus_polygon[i]);   //验证点是否在区域内
                if (result == true) {
                    campusMark.push(campus_polygon[i]);
                    campusMark.push(all_info[i]);
                    return campusMark;
                }
            }
        };
        map.addEventListener("click",function(e) {
            var pt = new BMap.Point(e.point.lng, e.point.lat);
            var myresult = polygonCheck(pt);
            if (myresult != null) {
                show_area(myresult[1].id,myresult[1].title)
            }
        });

        //地图加载完成
        map.addEventListener("tilesloaded",function(e) {
            com.loading_finished();
            setTimeout(function(){
                $('.map_loading').hide();
            },500)
        });

        if(area != ''){
            //行政区
            addDistrict(area);
            showArea(map_data);
        }else{
            //地区
            drawBoundary(area_data);
            showArea(map_data);
        }
        
    }


    var big_map_data = [],  //大地图数据
        small_map_data = [],
        xingzhengqu_status = true;
    axios.get(com.api.chaoyangqu).then(function(response){
        big_map_data = response.data.map;
        init_map();
    });


    //初始化地图
    init_map = function(){
        //请求朝阳区地图数据
        map_function('map_container',"朝阳区",big_map_data);
    };
    
    //清空地图dom
    map_clear = function(){
        $('.map_loading').show();
        $('.map_container').remove()
        $('.map_main').append('<div id="map_container" class="map_container"></div>');
        $('.map_container').height(main_height - 10);
    };

    show_area = function(id,name){
        //临时demo处理
        id = 0;
        name = "东风乡";

        if(xingzhengqu_status == false){
            window.location.href='/community_list.html';
            return false;
        };
        if(name != '东风乡'){
            alert('暂无'+name+'详细数据，请选取“东风乡”查看！');
            return false;
        };
        map_clear();
        //请求街乡地图数据
        axios.get(com.api.dongfengxiang).then(function(response){
            small_map_data = response.data.map;
            map_function('map_container',"",small_map_data,big_map_data[id].data);
            $('#active_area').html(name);
            xingzhengqu_status = false;
            hotPoints_data = [];
            map.setMinZoom(15);
            $('.ts_info').hide();
            $('.map_main').addClass('shequ').find('#3d').attr('href','http://localhost:8080/springMVC/v1/household/index?jd=东风乡');
        });
    }

    //地图重置
    map_recovery = function(){
        $('#active_area').html('朝阳区');
        map_clear();
        init_map();
        xingzhengqu_status = true;
        $('.ts_info').hide();
        $('.map_main').removeClass('shequ').find('#3d').attr('href','http://localhost:8080/springMVC/v1/household/index');
        setTimeout(function(){
            map.setMinZoom(12);
        },1000)
    };

    var myRM_arr = [],
        hotPoints_data = [],
        max_people_number = 0,
        heatmapOverlay,
        heatmap_show_status = false;
    show_cover = function(type){

        //切换数据
        var map_data = [];
        if(xingzhengqu_status == true){
            map_data = big_map_data;
        }else{
            map_data = small_map_data;
        };

        //切换覆盖物的时候清除之前覆盖物
        if(myRM_arr.length != 0){
            for (var i = 0; i < myRM_arr.length; i++) {
                map.removeOverlay(myRM_arr[i]);
            }
        };
        if(heatmap_show_status == true){
            map.removeOverlay(heatmapOverlay);
        };

        $('.ts_info').hide();
        //遍历添加覆盖物
        for (var i = 0; i < map_data.length; i++) {
            var c_point = new BMap.Point(map_data[i].center.lng,map_data[i].center.lat);

            var area_detail_data = '',
                number_color = '';

            //性别
            if(type == 'male'){
                area_detail_data = map_data[i].sex.m;
                 $('#type1').find('.color').removeClass('pink');
            };
            if(type == 'female'){
                area_detail_data = map_data[i].sex.f;
                number_color = 'pink';
                $('#type1').find('.color').addClass('pink');
            };

            //人口增长率
            if(type == 'growth_rate'){
                area_detail_data = map_data[i].growth_rate;
                if(map_data[i].growth_rate_max == 'max'){
                    number_color = 'max';
                };
                if(map_data[i].growth_rate_max == 'min'){
                    number_color = 'min';
                };
            };

            //房屋类型
            if(type == 'house_type_all'){
                area_detail_data = map_data[i].house_type.all;
            };
            if(type == 'house_type_weijian'){
                area_detail_data = map_data[i].house_type.weijian;
            };
            if(type == 'house_type_pingfang'){
                area_detail_data = map_data[i].house_type.pingfang;
            };
            if(type == 'house_type_bieshu'){
                area_detail_data = map_data[i].house_type.bieshu;
            };
            if(type == 'house_type_shangpin'){
                area_detail_data = map_data[i].house_type.shangpin;
            };
            if(type == 'house_type_other'){
                area_detail_data = map_data[i].house_type.other;
            };

            //房屋使用
            if(type == 'house_use_all'){
                area_detail_data = map_data[i].house_use.all;
            };
            if(type == 'house_use_zizhu'){
                area_detail_data = map_data[i].house_use.zizhu;
            };
            if(type == 'house_use_zuyong'){
                area_detail_data = map_data[i].house_use.zuyong;
            };
            if(type == 'house_use_shangyong'){
                area_detail_data = map_data[i].house_use.shangyong;
            };

            //房屋信息查询
            if(type == 'house_num'){
                area_detail_data = map_data[i].house_num;
            };

            //人口信息查询
            if(type == 'people_num'){
                area_detail_data = map_data[i].people_num;
            };

            var htm = '<div class="numBox '+number_color+'">'+area_detail_data+'</div>';

            if(type == 'hotPoints'){
                //人口密度热力图数据遍历
                hotPoints_data.push({"lng":map_data[i].center.lng,"lat":map_data[i].center.lat,"count":map_data[i].people_num});
                //遍历找出最大人口数值
                if(map_data[i].people_num > max_people_number){
                    max_people_number = map_data[i].people_num;
                };
            }else{
                htm+='<div class="hide id">'+map_data[i].data_id+'</div>';
                htm+='<div class="hide name">'+map_data[i].title+'</div>';
                var myRM= new BMapLib.RichMarker(htm, c_point,{"anchor":new BMap.Size(-15,15),"enableDragging":false});
                myRM_arr.push(myRM);
                map.addOverlay(myRM);

                myRM.addEventListener("onclick", function(e) {
                    if(xingzhengqu_status == false){
                        window.location.href='/community_list.html';
                        return false;
                    }else{
                        show_area($(e.target._content).eq(1)[0].innerText,$(e.target._content).eq(2)[0].innerText)
                    };
                }); 

            }
        };

        //
        if(type == 'hotPoints'){
            heatmapOverlay = new BMapLib.HeatmapOverlay({"radius":70});
            map.addOverlay(heatmapOverlay);
            heatmapOverlay.setDataSet({data:hotPoints_data,max:max_people_number});
            heatmap_show_status = true;
        };
        if(type == 'male' ||  type == 'female'){
            $('#type1').show();
        };
         if(type == 'growth_rate'){
            $('#type2').show();
        };
        if(type == 'people_num'){
            $('#type3').show();
        };
        if(type == 'house_num' || type == 'house_type_all' || type == 'house_type_weijian' || type == 'house_type_pingfang' || type == 'house_type_bieshu' || type == 'house_type_shangpin' || type == 'house_type_other' || type == 'house_use_all' || type == 'house_use_zizhu' || type == 'house_use_zuyong' || type == 'house_use_shangyong'){
            $('#type4').show();
        };

    };

    


    
});